/**
 * 解析时间获得年龄
 * @param nowDate 当前时间
 */
export const parseDateAge = (args: { year: number; month: number; day: number }, nowDate = new Date()) => {
  const { year, month, day } = args;
  const nowYear = nowDate.getFullYear();
  const nowMonth = nowDate.getMonth() + 1;
  const nowDay = nowDate.getDate();
  let age = nowYear - year - 1;
  if (month < nowMonth || (`${month}` === `${nowMonth}` && day <= nowDay)) {
    age += 1;
  }
  return age;
};

/**
 * 解析身份证
 * @param idCard 身份证号码
 * @param nowDate 当前时间
 */
export const parseIDCard = (idCard: string, nowDate = new Date()) => {
  const year = idCard.substring(6, 10);
  const month = idCard.substring(10, 12);
  const day = idCard.substring(12, 14);
  const birthday = `${year}-${month}-${day}`;
  const sex = window.parseInt(idCard.substr(16, 1), 10) % 2 === 1 ? '1' : '0';
  const age = parseDateAge(
    {
      year: window.parseInt(year, 10),
      month: window.parseInt(month, 10),
      day: window.parseInt(day, 10),
    },
    nowDate,
  );
  return {
    birthday,
    sex,
    age,
    year,
    month,
    day,
  };
};
